package com.excilys.capicsoubank.controllers;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.excilys.capicsoubank.services.TransactionService;
import com.excilys.capicsoubank.services.XlsDownloadService;

/**
 * Contrôleur gérant le téléchargement des fichiers excel.
 * 
 * @author Nicolas Poirier
 */
@Controller
@RequestMapping("/download")
public class DownloadController {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(DownloadController.class);

	@Autowired
	private XlsDownloadService downloadService;

	@Autowired
	private TransactionService transactionService;

	/**
	 * Retourne un fichier excel pour un compte, un mois et une année donnés.
	 * 
	 * @param response
	 *            la réponse renvoyée
	 * @param model
	 *            le modèle
	 * @param redirectAttributes
	 *            Le modèle pour la redirection
	 * @param accountId
	 *            l'id du compte demandé
	 * @param year
	 *            l'année demandée
	 * @param month
	 *            le mois demandé
	 * @param locale
	 *            la local pour la langue
	 * 
	 * @return La redirection si y'a
	 */
	@RequestMapping(value = "/xls/{accountId}/{year}/{month}")
	public String getXLS(HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes,
			@PathVariable("accountId") int accountId,
			@PathVariable("year") int year, @PathVariable("month") int month,
			Locale locale) {

		Object[] params = { accountId, year, month };
		LOGGER.debug("/download/xls/{}/{}/{}", params);

		Assert.isTrue(transactionService.isInHistory(year, month));

		try {
			HSSFWorkbook workbook = downloadService.downloadXLS(accountId,
					year, month, locale);

			StringBuilder fileName = new StringBuilder("account_")
					.append(accountId).append("_").append(month).append("_")
					.append(year).append(".xls");

			response.setHeader("Content-Disposition", "inline; filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");

			ServletOutputStream outputStream = response.getOutputStream();

			workbook.write(outputStream);

			outputStream.flush();
		} catch (IOException e) {
			return Template.error(e, "/home", redirectAttributes);
		}

		return null;
	}
}
